package com.genersoft.iot.vmp.utils;

/**
 * add by zhangming
 * 2022/11/2
 */
public class IPCheckUtil {

    public static final long a1 = getIpNum("10.0.0.0");
    public static final long a2 = getIpNum("10.255.255.255");
    public static final long b1 = getIpNum("172.16.0.0");
    public static final long b2 = getIpNum("172.31.255.255");
    public static final long c1 = getIpNum("192.168.0.0");
    public static final long c2 = getIpNum("192.168.255.255");
    public static final long d1 = getIpNum("10.44.0.0");
    public static final long d2 = getIpNum("10.69.0.255");

    public static boolean isInnerIP(String ip){
        long n = getIpNum(ip);
        return (n >= a1 && n <= a2) || (n >= b1 && n <= b2) || (n >= c1 && n <= c2) || (n >= d1 && n <= d2);
    }

    private static long getIpNum(String ipAddress) {
        String [] ip = ipAddress.split("\\.");
        long a = Integer.parseInt(ip[0]);
        long b = Integer.parseInt(ip[1]);
        long c = Integer.parseInt(ip[2]);
        long d = Integer.parseInt(ip[3]);
        return a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d;
    }

    //选择同网段的IP
    public static String selectSameNetIp(String sdpIp, String deviceIp) {
        String selectedIp = sdpIp;
        if(sdpIp.contains(",")){
            String[] ipArr = sdpIp.split(",");

            boolean bInner = IPCheckUtil.isInnerIP(deviceIp);
            for(String strIp : ipArr){
                if(bInner && IPCheckUtil.isInnerIP(strIp)){
                    selectedIp = strIp;
                    break;
                }

                if(!bInner && !IPCheckUtil.isInnerIP(strIp)){
                    selectedIp = strIp;
                    break;
                }
            }

        }
        return selectedIp;
    }
}
